#include "dbalertlog.h"
#include "dbapp.h"
#include <QSqlQuery>
#include <QDebug>
#include <QSqlError>
#include "mylogger.h"

using namespace ns_yht;

DbAlertLog::DbAlertLog()
{
}

DbAlertLog::~DbAlertLog()
{
}

bool DbAlertLog::checkTable()
{
    if (tableOk)
        return true;
    if (!DBAPP || !DATABASE.isOpen())
        return false;
    QSqlQuery query(DATABASE);
    QString strsql = QString::fromLocal8Bit("create table if not exists TAlertLog(ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, gid INTEGER, mtype INTEGER, mtime INTEGER, etime INTEGER, posted INTEGER DEFAULT 0);");
    if (!query.exec(strsql))
    {
        DBAPP->showErrorInfo("DbAlertLog::checkTable - create", query);
        return false;
    }

    strsql = QString::fromLocal8Bit("PRAGMA table_info(TAlertLog);");
    if (!query.exec(strsql))
    {
        DBAPP->showErrorInfo("DbAlertLog::checkTable - tableinfo", query);
        return false;
    }
    bool postedOk = false;
    while (query.next())
    {
        if (query.value(1).toString() == "posted")
        {
            postedOk = true;
            break;
        }
    }
    if (!postedOk)
    {
        strsql = QString::fromLocal8Bit("ALTER TABLE TAlertLog ADD COLUMN posted INTEGER DEFAULT 0;");
        if (!query.exec(strsql))
        {
            DBAPP->showErrorInfo("DbAlertLog::checkTable - alter", query);
            return false;
        }
    }

    tableOk = true;
    return true;
}

bool DbAlertLog::getList(QVector<QSharedPointer<ModelMsg>> &modelList)
{
    if (!checkTable())
        return false;
    QSqlQuery query(DATABASE);
    query.prepare("select id,gid,mtype,mtime,etime from TAlertLog");
    if (!query.exec())
    {
        DBAPP->showErrorInfo("DbAlertLog::getList", query);
        return false;
    }
    else
    {
        modelList.clear();
        while (query.next())
        {
            QSharedPointer<ModelMsg> model(new ModelMsg);
            model->id = query.value("id").toInt();
            model->ID = query.value("gid").toInt();
            model->type = query.value("mtype").toInt();
            model->time = query.value("mtime").toLongLong();
            model->expiredTime = query.value("etime").toLongLong();
            modelList.append(model);
        }
        return true;
    }
}

bool DbAlertLog::getUnPostedList(QVector<QSharedPointer<ModelMsg>> &modelList)
{
    if (!checkTable())
        return false;
    QSqlQuery query(DATABASE);
    query.prepare("select id,gid,mtype,mtime,etime from TAlertLog where posted = 0");
    if (!query.exec())
    {
        DBAPP->showErrorInfo("DbAlertLog::getUnPostedList", query);
        return false;
    }
    modelList.clear();
    while (query.next())
    {
        QSharedPointer<ModelMsg> model(new ModelMsg);
        model->id = query.value("id").toInt();
        model->ID = query.value("gid").toInt();
        model->type = query.value("mtype").toInt();
        model->time = query.value("mtime").toLongLong();
        model->expiredTime = query.value("etime").toLongLong();
        modelList.append(model);
    }
    return true;
}

bool DbAlertLog::getList(QVector<QSharedPointer<ModelMsg>> &modelList, int type, qint64 beginTime, qint64 endTime)
{
    if (!checkTable())
        return false;
    QSqlQuery query(DATABASE);
    QString strsql;
    if (type < 0)
        strsql = QString("select id,gid,mtype,mtime,etime from TAlertLog where mtime >= %1 and mtime <= %2").arg(beginTime).arg(endTime);
    else
        strsql = QString("select id,gid,mtype,mtime,etime from TAlertLog where mtype >= %1 and mtype<= %2 and mtime >= %3 and mtime <= %4").arg(type * 100).arg(type * 100 + 99).arg(beginTime).arg(endTime);
    query.exec(strsql);
    if (!query.exec())
    {
        DBAPP->showErrorInfo("DbAlertLog::getList", query);
        return false;
    }
    else
    {
        modelList.clear();
        while (query.next())
        {
            QSharedPointer<ModelMsg> model(new ModelMsg);
            model->id = query.value("id").toInt();
            model->ID = query.value("gid").toInt();
            model->type = query.value("mtype").toInt();
            model->time = query.value("mtime").toLongLong();
            model->expiredTime = query.value("etime").toLongLong();
            modelList.append(model);
        }
        return true;
    }
}

bool DbAlertLog::save(ModelMsg *model, bool posted)
{
    if (!checkTable())
        return false;
    QSqlQuery query(DATABASE);
    if (model->id == 0)
        query.prepare(QString("insert into TAlertLog(gid,mtype,mtime,etime,posted) values(%1,%2,%3,%4,%5)")
                          .arg(model->ID)
                          .arg(model->type)
                          .arg(model->time)
                          .arg(model->expiredTime)
                          .arg(posted ? 1 : 0));
    else
        query.prepare(QString("update TAlertLog set gid=%1,mtype=%2,mtime=%3,etime=%4,posted =%5 where id=%6")
                          .arg(model->ID)
                          .arg(model->type)
                          .arg(model->time)
                          .arg(model->expiredTime)
                          .arg(posted ? 1 : 0)
                          .arg(model->id));

    if (!query.exec())
    {
        DBAPP->showErrorInfo("DbAlertLog::save", query);
        return false;
    }
    if (model->id == 0)
        model->id = query.lastInsertId().toInt();
    return true;
}

bool DbAlertLog::updatePosted()
{
    if (!checkTable())
        return false;
    QSqlQuery query(DATABASE);
    query.prepare("update TAlertLog set posted = 1 where posted = 0");
    if (!query.exec())
    {
        DBAPP->showErrorInfo("DbAlertLog::updatePosted", query);
        return false;
    }
    return true;
}

bool DbAlertLog::deleteOne(int id)
{
    if (!checkTable())
        return false;
    QSqlQuery query(DATABASE);
    query.prepare(QString("delete from TAlertLog where id=%1").arg(id));
    if (!query.exec())
    {
        DBAPP->showErrorInfo("DbAlertLog::deleteOne", query);
        return false;
    }
    return true;
}

bool DbAlertLog::getList(QVector<QSharedPointer<ModelMsg>> &modelList, int pageIndex, int pageSize)
{
    if (!DBAPP || !DATABASE.isOpen() || !checkTable())
        return false;
    QSqlQuery query(DATABASE);
    // QString strSql = "select ";
    // if (pageIndex >= 0 && pageSize > 1)
    // {
    //     strSql += "ROW_NUMBER() OVER (ORDER BY mtime) AS RowNumber, ";
    // }
    // strSql += QString(" id,gid,mtype,mtime,etime from TAlertLog ");

    // if (pageIndex >= 0 && pageSize > 0)
    // {
    //     strSql += QString(" limit %1,%2").arg(pageIndex * pageSize).arg(pageSize);
    // }
    QString strSql = QString("select id,gid,mtype,mtime,etime from TAlertLog order by mtime limit %1,%2").arg(pageIndex * pageSize).arg(pageSize);

    query.prepare(strSql);

    if (!query.exec())
    {
        qDebug() << "DbAlertLog::getList_page.lastError()----" << query.lastError();
        return false;
    }
    modelList.clear();
    while (query.next())
    {
        QSharedPointer<ModelMsg> model(new ModelMsg);
        model->id = query.value("id").toInt();
        model->ID = query.value("gid").toInt();
        model->type = query.value("mtype").toInt();
        model->time = query.value("mtime").toLongLong();
        model->expiredTime = query.value("etime").toLongLong();
        modelList.append(model);
    }

    return true;
}

int DbAlertLog::getCount()
{
    if (!DBAPP || !DATABASE.isOpen() || !checkTable())
        return 0;
    QSqlQuery query(DATABASE);
    query.prepare("select count(*) from TAlertLog");
    if (!query.exec())
    {
        DBAPP->showErrorInfo("DbAlertLog::getCount", query);
        return 0;
    }
    query.next();
    return query.value(0).toInt();
}

bool DbAlertLog::removeBefore(qint64 ctime)
{
    if (!DBAPP || !DATABASE.isOpen() || !checkTable())
        return false;
    QSqlQuery query(DATABASE);
    QString strsql = QString("delete from TAlertLog where mtime<%1").arg(ctime);
    if (!query.exec(strsql))
    {
        QSqlError str = query.lastError();
        QString strerror = str.text();
        qDebug() << "DbAlertLog::removeBefore.lastError()----------------------" << strerror;
        return false;
    }
    return true;
}
